<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Bank;
use app\common\model\MoneyLog;
use app\common\model\ScoreLog;
use app\common\model\User as ModelUser;
use app\common\model\user\Daydiviend;
use app\common\model\user\Dividendlog;
use app\common\model\user\Level;
use app\common\model\user\Withdrawal;
use fast\Random;
use think\Config;
use think\Db;
use think\Env;
use think\model\Collection;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'wxapplogin', 'is_register'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $userInfo = ModelUser::get($this->auth->id);
        $userInfo->userlevel;
        $userInfo['withdraw_money'] = Withdrawal::where('user_id', $this->auth->id)->sum('money') ?? 0;
        $this->responseMsg(0, $userInfo);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * @Author LK
     * @ApiTitle (添加/编辑银行卡)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=false, sample="", description="银行卡ID")
     * @ApiParams (name="cardholder", type="string", required=true, sample="", description="持卡人")
     * @ApiParams (name="bank_name", type="string", required=true, sample="", description="银行")
     * @ApiParams (name="outlets", type="string", required=true, sample="", description="网点")
     * @ApiParams (name="account", type="string", required=true, sample="", description="账号")
     * @ApiParams (name="is_default", type="string", required=true, sample="", description="是否默认(1为默认)")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function add_bank()
    {
        $param = request()->param();
        extract($param);
        $param['user_id'] = $this->auth->id;
        if (isset($id) && $id) {
            $bank = Bank::get($id);
            if (!$bank) {
                $this->error('银行卡不存在');
            }
            $res = $bank->allowField(true)->save($param);
        } else {
            $res = Bank::create($param, true);
        }
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (获取默认银行卡)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function get_bank()
    {
        $list = Bank::get(['user_id' => $this->auth->id, 'is_default' => 1]);
        $this->success('成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (银行卡列表)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function bank_list()
    {
        $list = Bank::all(['user_id' => $this->auth->id]);
        $this->success('成功', $list);
    }

    /**
     * @Author LK
     * @ApiTitle (银行卡删除)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function del_bank()
    {
        $id = request()->param('id');
        if (!$id) {
            $this->error('参数错误');
        }
        $res = Bank::where('id', $id)->delete();
        if ($res) {
            $this->success('成功');
        }
        $this->error('失败');
    }

    /**
     * @Author LK
     * @ApiTitle (提现)
     * @ApiMethod (POST)
     * @ApiParams (name="money", type="integer", required=true, sample="", description="提现金额")
     * @ApiParams (name="type", type="integer", required=true, sample="", description="1=微信提现,2=支付宝,3=银行卡")
     * @ApiParams (name="image", type="string", required=true, sample="", description="发票")
     * @ApiParams (name="account", type="string", required=false, sample="", description="账号")
     * @ApiParams (name="bank_id", type="string", required=false, sample="", description="银行卡id")
     * @ApiParams (name="mark", type="string", required=false, sample="", description="备注")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawal()
    {
        $post = $this->request->post();
        $user = ModelUser::get($this->auth->id);
        extract($post);
        $validate = validate('user.Withdrawal'); //使用助手函数
        if ($type == 1) {
            $scene = 'wechat';
        } elseif ($type == 2) {
            $scene = 'alipay';
        } elseif ($type == 3) {
            $scene = 'bank';
        }
        $result = $validate->scene($scene)->check($post);
        if (!$result) {
            $this->error($validate->getError());
        }
        $withdrawal_commission = config('site.withdrawal_commission');
        if ($withdrawal_commission > 0 && $withdrawal_commission <= 100) {
            $withdrawal_commission_fee = bcdiv($withdrawal_commission, 100, 2);
            $handling_charge = bcmul($money, $withdrawal_commission_fee, 2);
        } else {
            $handling_charge = 0;
        }
        if ($type == 3) {
            $bank = Bank::get($bank_id);
            $post['account'] = $bank->account;
        }
        $post['sn'] = sn('user_withdrawal', 'sn', 'TX');
        $post['user_id'] = $user['id'];
        // $post['image'] = $image;
        $post['handling_charge'] = $handling_charge;
        $post['amount_received'] = bcsub($money, $handling_charge, 0);
        $post['type'] = $type;
        Db::startTrans();
        try {
            $tx = new Withdrawal($post);
            $tx->allowField(true)->save();
            ModelUser::money(-$money, $user['id'], '提现金额', ['class' => 'withdraw']);
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('申请成功');
    }
    /**
     * @Author LK
     * @ApiTitle (用户提现记录)
     * @ApiMethod (get)
     * @ApiParams (name="state", type="integer", required=true, sample="", description="all=全部,1=提现中,2=提现成功,3=提现失败")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function withdrawalLog()
    {
        $get = request()->get();
        extract($get);
        $withdrawal = new Withdrawal;
        if ($state != 'all') {
            $withdrawal->where('state', $state);
        }
        $withdrawal->where('user_id', $this->auth->id);
        $withdrawal->order('createtime desc');
        $list = $withdrawal->field("*,FROM_UNIXTIME(createtime,'%Y-%m-%d') as create_time")->paginate(10);
        foreach ($list as $key => $v) {
            $v->bank;
        }
        $this->success('', $list);
    }

    /**
     * 我的粉丝
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="integer", required=true, sample="1", description="页码")
     * @ApiParams (name="keyword", type="str", required=false, sample="1", description="搜索")
     * @ApiParams (name="type", type="integer", required=false, sample="1", description="类型:''=全部,1=一级,2=二级")
     * @ApiParams (name="level_id", type="integer", required=false, sample="1", description="等级")
     * 
     * @ApiParams (name="order_type", type="str", required=true, sample="1", description="排序类型:team_num=团队,team_consume=团队营业额,team_order_num=团队订单量,level_id=等级")
     * @ApiParams (name="order_sort", type="str", required=true, sample="1", description="排序方式:asc=升序,desc=降序")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function myfans()
    {
        $user = $this->auth->getUser();
        $model = new ModelUser();
        if ($this->request->post('keyword')) {
            $model->where('mobile|nickname', 'like', "%{$this->request->post('keyword')}%")->where('find_in_set(:id,team_tag)', ['id' => $user->id]);
        } elseif ($this->request->post('type') == 1) {
            $model->where('pid', $user->id);
        } elseif ($this->request->post('type') == 2) {
            $ids = ModelUser::where('pid', $user->id)->column('id');
            if (!count($ids)) {
                $this->responseMsg(0, []);
            }
            $model->where('pid', 'in', $ids);
        } else {
            $model->where('find_in_set(:id,team_tag)', ['id' => $user->id]);
        }
        if ($this->request->post('level_id')) {
            $model->where('level_id', $this->request->post('level_id'));
        }

        $res = $model->order("{$this->request->post('order_type')} {$this->request->post('order_sort')}")->field('id,team_tag,nickname,mobile,avatar,team_num,team_consume,team_order_num,level_id')->paginate(10);

        foreach ($res as $u) {
            $ids = explode(',', $u->team_tag);
            $ids  = array_reverse($ids);
            $u->fans_level = array_search($user->id, $ids);
            $u->userlevel;
        }
        $this->responseMsg(0, $res);
    }


    /**
     * 佣金明细
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="starttime", type="str", required=false, sample="", description="开始时间 2023-05-06")
     * @ApiParams (name="endtime", type="str", required=false, sample="", description="结束时间 2023-05-06")
     * @ApiParams (name="type", type="integer", required=false, sample="1", description="类型:1=收入,2=支出")
     * @ApiParams (name="page", type="integer", required=true, sample="1", description="页码")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function moneylog()
    {
        $user = $this->auth->getUser();
        $model = new MoneyLog();
        if ($this->request->post('starttime')) {
            $model->where('createtime', '>=', strtotime($this->request->post('starttime')));
        }
        if ($this->request->post('endtime')) {
            $model->where('createtime', '<', strtotime($this->request->post('endtime')) + 86400);
        }
        if ($this->request->post('type') == 1) {
            $model->where('money', '>=', 0);
        } elseif ($this->request->post('type') == 2) {
            $model->where('money', '<', 0);
        }
        $model->where('user_id', $this->auth->id);
        $model->order('id desc');
        $list = $model->paginate(10);
        $this->success('', $list);
    }

    /**
     * 积分明细
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="starttime", type="str", required=false, sample="", description="开始时间 2023-05-06")
     * @ApiParams (name="endtime", type="str", required=false, sample="", description="结束时间 2023-05-06")
     * @ApiParams (name="type", type="integer", required=false, sample="1", description="类型:1=收入,2=支出")
     * @ApiParams (name="page", type="integer", required=true, sample="1", description="页码")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function scorelog()
    {
        $model = new ScoreLog();
        if ($this->request->post('starttime')) {
            $model->where('createtime', '>=', strtotime($this->request->post('starttime')));
        }
        if ($this->request->post('endtime')) {
            $model->where('createtime', '<', strtotime($this->request->post('endtime')) + 86400);
        }
        if ($this->request->post('type') == 1) {
            $model->where('score', '>=', 0);
        } elseif ($this->request->post('type') == 2) {
            $model->where('score', '<', 0);
        }
        $model->where('user_id', $this->auth->id);
        $model->order('id desc');
        $list = $model->paginate(10);
        $this->success('', $list);
    }


    /**
     * 已提现佣金
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="page", type="integer", required=true, sample="1", description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function withdrawmoneylog()
    {
        $user = $this->auth->getUser();
        $model = new MoneyLog();
        if ($this->request->post('starttime')) {
            $model->where('createtime', '>=', strtotime($this->request->post('starttime')));
        }
        if ($this->request->post('endtime')) {
            $model->where('createtime', '<', strtotime($this->request->post('endtime')) + 86400);
        }
        if ($this->request->post('type') == 1) {
            $model->where('money', '>=', 0);
        } elseif ($this->request->post('type') == 2) {
            $model->where('money', '<', 0);
        }
        $model->where('user_id', $this->auth->id);
        $model->where('class', 'withdraw');
        $model->order('id desc');
        $list = $model->paginate(10);
        $total_money = MoneyLog::where('user_id', $this->auth->id)->where('class', 'withdraw')->where('money', '<', 0)->sum('money');
        $list = $list->toArray();
        $list['total_money'] = abs($total_money);
        // $total_money = 1;
        $this->success('', $list);
    }




    /**
     * 分红值明细
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="starttime", type="str", required=false, sample="", description="开始时间 2023-05-06")
     * @ApiParams (name="endtime", type="str", required=false, sample="", description="结束时间 2023-05-06")
     * @ApiParams (name="page", type="integer", required=true, sample="1", description="页码")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function dividendlog()
    {
        $user = $this->auth->getUser();
        $model = new Dividendlog();
        if ($this->request->post('starttime')) {
            $model->where('createtime', '>=', strtotime($this->request->post('starttime')));
        }
        if ($this->request->post('endtime')) {
            $model->where('createtime', '<', strtotime($this->request->post('endtime')) + 86400);
        }


        $model->where('user_id', $this->auth->id);
        $model->order('id desc');
        $list = $model->paginate(10);
        $this->success('', $list);
    }

    /**
     * 团队成员
     * @Author xy
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function teamuser()
    {
        $user = $this->auth->getUser();

        // $res= ModelUser::alias('u')->where("find_in_set({$user->id},team_tag)")->join('fa_user_level level','u.level_id=level.id','right')->group('level.id')->field('count(u.*) as num,level.name')->select();
        // $sql = 
        $res = Collection(Level::alias('l')->join('fa_user u', "u.level_id=l.id and find_in_set({$user->id},u.team_tag)", 'left')->where('l.id', '<', 8)->group('l.id')->field('l.id,l.name,count(u.id) AS num')->select())->toArray();
        $has = 0;

        if ($user->level_id >= 4) {
            $all = Daydiviend::order('num asc')->select();
            foreach ($all as $key => $d) {
                if ($user->today_share_vip < $d->num) {
                    if ($has > $d->num - $user->today_share_vip) {
                        $has = $d->num - $user->today_share_vip;
                        break;
                    }

                    // break;
                } elseif ($user->today_share_vip == $d->num) {
                    $has = $d->num;
                } else {
                    $has = $d->num - ($user->today_share_vip % $d->num);
                }
            }
        }
        array_unshift($res, [
            'id' => 0,
            'name' => '体验用户',
            'num' => ModelUser::where('find_in_set(:id,team_tag)', ['id' => $user->id])->whereNull('level_id')->where('is_exp', 1)->count()
        ]);
        $this->responseMsg(0, ['list' => $res, 'vip' => ['has' => $has, 'current' => $user->today_share_vip]]);
    }

    /**
     * 小程序登录
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="string", required=true, description="微信CODE")
     * @ApiParams (name="phonecode", type="string", required=true, description="手机号code")
     * @ApiParams (name="user_info", type="jsonstring", required=true, description="用户信息")
     * @ApiParams (name="pid", type="int", required=false, description="上级用户ID")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':'1','msg':'返回成功'})
     */
    public function wxapplogin()
    {


        $code = $this->request->post('code');

        $user_info = $this->request->put();
        $pid = $this->request->post('pid');


        //获取用户openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?";
        $appid = Env::get('wx.appid');
        $appsecret = Env::get('wx.appsecret');


        $param = array(
            "appid" => $appid,
            "secret" => $appsecret,
            "js_code" => $code,
            "grant_type" => "authorization_code"
        );

        $client = new \GuzzleHttp\Client();

        $response = $client->get($url, [
            'query' => $param
        ]);
        $res = $response->getBody();

        $res = json_decode($res, 1);
        if (!array_key_exists('errcode', $res)) {
            $openid = $res['openid'] ?? '';

            $token = get_wx_token($appid, $appsecret);
            $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";

            // $code = $this->request->post('phonecode');
            $client = new \GuzzleHttp\Client();

            $response = $client->post($url, [
                'json' => [        //参数组
                    'code' => $this->request->post('phonecode')
                ]
            ]);
            $pres = $response->getBody();

            $pres = json_decode($pres, 1);

            if ($pres['errcode'] == 0) {

                $data = $pres['phone_info'];
                $user_info = $user_info['user_info'] ?? [];
                $user_info['mobile'] = $data['phoneNumber'] ?? '';
                $user = ModelUser::followuser($openid, $user_info, $pid);
                $user_id = $user->id;
            } else {
                $this->responseMsg($pres['errcode'], '1111', $pres['errmsg']);
            }

            //创建更新用户信息

        } else {
            $this->responseMsg(2041, $res, 'openid获取失败');
        }

        $this->auth->direct($user_id);

        $this->responseMsg(0, $this->auth->getUserinfo());
    }

    /**
     * 分享海报二维码
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiSummary ()
     * @ApiBody ()
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function share()
    {
        $user = $this->auth->getUser();
        $qr_code = ModelUser::getQrcode($user);

        $share_posters = config('site.share_image');
        $total_son = ModelUser::where('pid', $user->id)->count();
        $this->responseMsg(0, ['qr_image' => $qr_code['data'] ?? '', 'poster_image' => $share_posters, 'total_son' => $total_son]);
    }

    /**
     * 绑定上级
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="上级ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function bindpid()
    {
        $user = $this->auth->getUser();
        $rej = $this->validate(
            $this->request->post(),
            [
                'id' => 'require|gt:0',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }

        if ($user->pid) {
            $this->responseMsg(1005, [], '已有上级');
        }

        if ($this->request->post('id') == $user->id) {
            $this->responseMsg(1005, [], '不能绑定自己');
        }
        $puser = ModelUser::where('id', $this->request->post('id'))->find();
        if (!$puser) {
            $this->responseMsg(1005, [], '错误的ID');
        }
        if ($puser->pid == $user->id) {
            $this->responseMsg(1005, [], '不能互为上级');
        }

        $user->pid = $puser->id;
        $user->save();


        $u = ModelUser::find($user->id);
        $ids = explode(',', $u->team_tag);
        array_pop($ids);
        ModelUser::where('id', 'in', $ids)->inc('team_num', 1)->update();

        foreach ($ids as $id) {
            $us = ModelUser::get($id);
            if ($us && $us->level_id < 5) {
                Level::checkUP($us);
            }
        }
        // var_dump($u->pid);
        // $sql = "update fa_user set team_num=(select count(*) from )"


        $this->responseMsg(0);
    }

    /**
     * 全部等级
     * @Author xy
     * @ApiMethod (POST)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function alllevel()
    {
        $res = Level::where('id', '<', 8)->order('id asc')->field('id,name')->select();
        $this->responseMsg(0, $res);
    }

    /**
     * 转账
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="str", required=true, sample="", description="对方手机号")
     * @ApiParams (name="money", type="integer", required=true, sample="", description="金额")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function transfer()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'mobile'  => 'require',
                'money'  => 'require|gt:0',

            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $user = $this->auth->getUser();
        $to_user = ModelUser::where('mobile', $this->request->post('mobile'))->find();
        if (!$to_user) {
            $this->responseMsg(1, '', '未找到该手机号用户');
        }
        $money = abs($this->request->post('money'));
        if ($user->money < $money) {
            $this->responseMsg(1, '', '余额不足');
        }
        ModelUser::money(-$money, $user->id, '转出到【' . $to_user->mobile . '】');
        ModelUser::money($money, $to_user->id, '【' . $user->mobile . '】转入');
        $this->responseMsg(0);
    }

    /**
     * 查询用户
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="str", required=true, sample="", description="手机号")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function search_user()
    {
        $mobile = $this->request->post('mobile');
        $user = ModelUser::get(['mobile' => $mobile]);
        if (!$user) {
            $this->responseMsg(1, '', '当前用户不存在,请核对号码后重新输入');
        }
        if ($mobile == $this->auth->getUser()->mobile) {
            $this->responseMsg(1, '', '您不能向自己转出余额,请选择他人');
        }
        $this->responseMsg(0, $user);
    }

    /**
     * 检查是否注册
     * @Author xy
     * @ApiMethod (POST)
     * @ApiParams (name="code", type="integer", required=true, sample="", description="微信CODE")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    function is_register()
    {
        $user_info = $this->request->post('user_info');
        $code = $this->request->post('code');



        //获取用户openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?";
        $appid = Env::get('wx.appid');
        $appsecret = Env::get('wx.appsecret');


        $param = array(
            "appid" => $appid,
            "secret" => $appsecret,
            "js_code" => $code,
            "grant_type" => "authorization_code"
        );

        $client = new \GuzzleHttp\Client();

        $response = $client->get($url, [
            'query' => $param
        ]);
        $res = $response->getBody();

        $res = json_decode($res, 1);
        if (!array_key_exists('errcode', $res)) {
            $openid = $res['openid'] ?? '';
            $has = ModelUser::where('openid', $openid)->find();
            if ($has && $has->avatar && $has->avatar != '/assets/img/avatar.png') {
                $this->responseMsg(0, 1);
            }
            $this->responseMsg(0, 0);
        } else {
            $this->responseMsg(2041, $res, 'openid获取失败');
        }
    }
}
